#coding=utf-8
#智游天下的接口
from __future__ import division

import ujson,datetime
from django.shortcuts import render_to_response, HttpResponse, HttpResponseRedirect
from django.db.models import Count,Sum,Max

from  websys import (
    db_redis,webconfig,fun
)
import  websys.ReturnCode as errcode
from websys.models import UserInfo,GameRecord,WithholdInfo,TableInfo#,IdentCode
from websys.view.mjhall import user_get_agent_id,user_pre_share
from django.conf.urls import patterns, url
from django.views.decorators.csrf import csrf_exempt
import mjhall

urlpatterns = patterns('',
                         #其它。。。。。。。。。。。。。
                       #获取用户信息
                       url(r'^userinfo', 'websys.view.mjhall_zytx.user_getinfo', name='user_getinfo'),
                       #实名认证
                       url(r'^idcard_ident', 'websys.view.mjhall_zytx.user_idcard_ident', name='user_idcard_ident'),
                       #绑定手机
                       url(r'^bind_phone', 'websys.view.mjhall_zytx.user_bind_phone', name='user_bind_phone'),
                       #获取验证码
                       url(r'^get_code', 'websys.view.mjhall_zytx.user_ident_code', name='user_ident_code'),
                       #代开房间记录
                       url(r'^agent_gameroom', 'websys.view.mjhall_zytx.user_get_agentroom', name='user_get_agentroom'),
                       #我的房间列表
                       url(r'^myroom', 'websys.view.mjhall_zytx.user_get_myroom', name='user_get_myroom'),
                       #战绩
                       url(r'^gamerecord', 'websys.view.mjhall_zytx.user_get_gamerecord', name='user_get_gamerecord'),
                       #获取战绩小局user_each_gamerecord
                       url(r'^recorddetail', 'websys.view.mjhall_zytx.user_each_gamerecord', name='user_each_gamerecord'),)

#游戏对应的人数
GAME_TO_NUMBER={54:5,55:5,56:5,2000:4,4000:4}
IS_TEST=0

#等级换算
def getgrade(num):
    n = 0
    a = 4
    if 0<=num <100:
        return 1
    elif 100<=num <200:
        return 2
    elif 200<=num <300:
        return 3
    else:
        grade = None
        while grade==None:
            if (300+n)<=num <(500+n):
                grade =a
                return grade
            else:
                n +=200
                a +=1

#判断get方式传的参数名是否正确
def check_args(args,args2):
    return len(set(args2)-set(args.keys()))>0
    # n = 0
    # for i in args:
    #     if i in args2:
    #         n +=1
    # return n





#实名认证
# http://127.0.0.1:8080/api/hall/zy/idcard_ident?user_id=1&idcard=430482199411168075&truename=张三
#user_id玩家，idcard身份证，truename真实姓名
#{'msg':'ident success','code':0}
def user_idcard_ident(request):
    objs = {'msg':'','code':0}
    data = fun.Decode_Request_MJ(request)
    fun.add_log(data)
    user_uid=None
    if request.method =='GET':
        args_list =['idcard','truename','user_id']
        if check_args(data,args_list):
            objs['msg'] = 'error parms'
            objs['code'] = errcode.ParamError
            return HttpResponse(ujson.dumps(objs))
        user_uid = data['user_id']
    if request.method =='POST':
        user_uid = request.POST.get('user_id',None)

    if not UserInfo.objects.filter(pk=user_uid).exists():
        objs['msg'] = 'id error'
        objs['code'] = errcode.UserNotExists
        return HttpResponse(ujson.dumps(objs))

    UserInfo.objects.filter(id=user_uid).update(idcard=data['idcard'],truename=data['truename'])
    objs['msg'] = 'ident success'
    return HttpResponse(ujson.dumps(objs))



#绑定手机号
# http://127.0.0.1:8080/api/hall/zy/bind_phone?user_id=1&phone=15570151890&code=123456
#user_id玩家，phone电话号码,code验证码
#{'msg':'ident success','code':0}
def user_bind_phone(request):
    objs = {'msg':'','code':0}
    data = fun.Decode_Request_MJ(request)
    fun.add_log(data)
    user_id = None
    if request.method =='GET':
        args_list = ['user_id','phone','code']
        if check_args(data,args_list):
            objs['msg'] = 'parms error'
            objs['code'] = errcode.ParamError
            return HttpResponse(ujson.dumps(objs))
        user_id = data['user_id']
    if request.method =='POST':
        user_id = request.POST.get('user_id',None)

    infos = IdentCode.objects.get(user_id=user_id).ident_code
    print infos
    if int(data['code']) ==infos:
        objs['msg'] = 'success'
        return HttpResponse(ujson.dumps(objs))
    else:
        objs['msg'] = 'code error'
        objs['code'] = errcode.CodeError
        return HttpResponse(ujson.dumps(objs))



# http://127.0.0.1:8080/api/hall/zy/get_code?user_id=1&phone=15570151890
#user_id玩家，phone电话号码
#{'msg':'ident success','code':0}
#获取验证码
def user_ident_code(request):
    objs = {'msg':'','code':0}
    data = fun.Decode_Request_MJ(request)
    fun.add_log(data)
    user_id = None
    code = 123456
    # guess = ''.join([str(i) for i in random.sample(range(0, 9), 6)])
    # code = int(guess)
    if request.method =='GET':
        args_list = ['user_id','phone']
        if check_args(data,args_list):
            objs['msg'] = 'parms error'
            objs['code'] = errcode.ParamError
            return HttpResponse(ujson.dumps(objs))
        user_id = data['user_id']
    if request.method =='POST':
        user_id = request.POST.get('user_id',None)

    IdentCode.objects.create(user_id=user_id,phone=data['phone'],ident_code=code)

    objs['msg'] = 'success'
    return HttpResponse(ujson.dumps(objs))


#获取用户信息
#http://127.0.0.1:8080/api/hall/zy/userinfo?uid=1

def user_getinfo(request):
    t_obj=fun.Decode_Request_MJ(request)
    fun.add_log(t_obj)

    t_uid=None
    t_data={'code':-1,'msg':'','data':{}}
    if request.method == 'GET':
        if 'uid' not in t_obj:
            t_data['msg']="error parms"
            return HttpResponse(ujson.dumps(t_data))
        t_uid = t_obj['uid']
    elif request.method == 'POST':
        t_uid = request.POST.get('uid',None)

    if not t_uid:
        t_data['msg']="empty openid"
        return  HttpResponse(ujson.dumps(t_data))

    #判断是否存在
    if(UserInfo.objects.filter(pk=t_uid).exists()):
        u_info=UserInfo.objects.get(pk=t_uid)

    else:#新增
        t_data['msg']="uid not exists "
        t_data['code']=errcode.UserNotExists
        return  HttpResponse(ujson.dumps(t_data))

    grade = fun.getgrade(u_info.gamepoint)

    #返回值
    t_res={"id": u_info.id,"name": u_info.nickname,"avatar": fun.GetImgURL(request,u_info.head_img),"diamond": u_info.gamepoint,
           'status':u_info.status,'grade':grade,'idcard':u_info.idcard,'truename':u_info.truename,'phone':u_info.phone,
            'autograph':u_info.autograph,'gender':u_info.gender,'agent_id':user_get_agent_id(u_info),'isShared':user_pre_share(t_uid)}

    t_data['code']= 0
    t_data['msg'] = 'success'
    t_data['data']=t_res
    return HttpResponse(ujson.dumps(t_data))





#替他人开房记录
#http://127.0.0.1:8080/api/hall/zy/agent_gameroom?user_id=95&create_type=1
#user_id玩家ID，create_type是否为代开
#{'msg':success,'code':0,'room_count':2,'user_info':[{'game_type':'牛牛','roomid':201654,
# 'playnum':4,'openparam':{"99":7,"100":4,"2":15},'game_status':0,'create_time':'2017-06-22 19:08:53'},{...............}]}
# room_count房间数量,game_type游戏类型，roomid房间号，playnum房间人数，openparam游戏玩法、局数，
#game_statue游戏状态,create_time创建时间。
def user_get_agentroom(request):
    objs = {'msg':'','code':0,'room_count':0,'room_infos':[]}
    data = fun.Decode_Request_MJ(request)
    fun.add_log(data)
    user_id = None
    create_type = None
    if request.method =='GET':
        args_list = ['user_id','create_type']
        if check_args(data,args_list):
            objs['msg'] = 'parms error'
            objs['code'] = errcode.ParamError
            return HttpResponse(ujson.dumps(objs))
        user_id = data['user_id']
        create_type = data['create_type']
    if request.method =='POST':
        user_id = request.POST.get('user_id',None)

    # count = TableInfo.objects.filter(uid=user_id).filter(create_type=data['create_type']).count()
    # if count >0:
    #     infos = TableInfo.objects.filter(uid=user_id).filter(create_type=data['create_type'])
    date_from=fun.GetTime_ByNow()
    infos = TableInfo.objects.filter(uid=user_id,create_time__gte=date_from,create_type=create_type,game_status__in=webconfig.ROOM_NORMAL_STATUS)
    t_arr = []
    for i in infos:
        tmp_data={}
        #for i in infos:
        tmp_data['gameid'] = i.gameid_id
        tmp_data['roomid'] = i.roomid
        tmp_data['currentround'] = i.round
        tmp_data['openparam'] = i.openparam
        tmp_data['game_status'] = i.game_status
        tmp_data['create_time'] = i.create_time
        t_arr.append(tmp_data)

    objs['room_count'] = len(infos)
    objs['room_infos'] = t_arr
    objs['msg'] = 'success'
    return HttpResponse(ujson.dumps(objs))
    # else:
    #     objs['msg'] = 'No agent_gameroom'
    #     return HttpResponse(ujson.dumps(objs))



#战绩
#http://127.0.0.1:8080/api/hall/zy/gamerecord?uid=1&gameid=55
#uid玩家帐号,gameid游戏类型id
#{'msg':'success',"code":0,'round_counts':8,'win_rounds':5,'data':[{'roomid':852645,'recordid':23424323423423234,,'create_time':1554569575,'status':1,'user_infos':
# [{'nickname':'张三','uid':486365,'head_img':002,'isbanker':1,'score':30},{'nickname':'guolimin','uid':486345,'head_img':005,'isbanker':0,'score':-30}]},
# {'...':'.....'}],'allscore':50}
#.............
#allscore成绩，round_counts总局数，win_rounds胜利
# data为房间记录列表,roomid房间号，recordid局编号,create_time开桌时间,status状态，user_infos为玩家数据，属性如下
# nikename为玩家昵称，uid玩家ID，head_img玩家头像，score分数，,isbanker是否房主(0,1)
@csrf_exempt
def user_get_gamerecord(request):
    objs={'code':0,'msg':'','data':{}}
    data=fun.Decode_Request_MJ(request)
    fun.add_log(data)
    user_id=None
    if request.method == 'GET':
        need_keys=['uid','gameid']
        if check_args(data,need_keys):#判断GET方式传入的参数名
            objs['msg']="error parms"
            objs['code'] = errcode.ParamError
            return HttpResponse(ujson.dumps(objs))

        user_id = int(data['uid'])
        game_id = int(data['gameid'])
    elif request.method == 'POST':
        user_id = request.POST.get('uid',None)

    if not UserInfo.objects.filter(pk=user_id).exists():
        objs['msg']='error uid'
        objs['code']=errcode.UserNotExists
        return HttpResponse(ujson.dumps(objs))
    date_from=fun.GetTime_ByNow(-webconfig.GAME_RECORD_DAY)#七天内
    cur_obj = GameRecord.objects.filter(uid_id=user_id,start_time__gte=date_from,gameid_id=game_id).aggregate(score=Sum("score"), num=Count("id"))
    counts = GameRecord.objects.filter(uid_id=user_id,start_time__gte=date_from,score__gt=0,gameid_id=game_id).count()
    t_data={'round_counts':0,'win_rounds':0,'allscore':0,'list':[]}
    t_data['round_counts'] = cur_obj['num']#总局数
    t_data['allscore'] = cur_obj['score']#总分
    t_data['win_rounds'] = counts#赢的局数
    #wh_info = WithholdInfo.objects.filter(uid_id=user_id,create_time__gte=date_from)
    my_tbs=GameRecord.objects.filter(uid_id=user_id,start_time__gte=date_from,gameid_id=game_id).values('roomid','recordid').annotate(score=Max('id')).order_by('-id')
    for each in my_tbs:#遍历每个房间的信息
        cur_roomid=each['roomid']
        cur_recordid=each['recordid']
        datas = {'roomid':cur_roomid,'recordid':cur_recordid,'create_time':-1,'status':-1}
        #房间信息
        # table_info = each.tableid
        # bank_uid=table_info.uid_id
        # datas['roomid'] = table_info.roomid
        # datas['recordid'] = table_info.recordid
        # datas['create_time'] = table_info.create_time
        # datas['status'] = table_info.game_status
        # print table_info.gameid_id,'--game_id != table_info.gameid_id---',game_id != table_info.gameid_id,
        # if (game_id >0) and (game_id != table_info.gameid_id):
        #     continue

        table_info=TableInfo.objects.get(roomid=cur_roomid,recordid=cur_recordid)
        bank_uid=table_info.uid_id
        datas['create_time'] = mjhall.DateTimeToTimetuple(table_info.create_time)
        datas['status'] = table_info.game_status
        #当桌的全部玩家
        all_infos = GameRecord.objects.filter(roomid=cur_roomid,recordid=cur_recordid,gameid_id=table_info.gameid_id).values('uid_id').annotate(score=Sum('score'))
        a = []
        for i in all_infos:
            a.append(i['uid_id'])
        u_info = UserInfo.objects.filter(id__in=a)
        u_data=[]#用户信息
        for i in all_infos:
            dics = {}
            for j in u_info:
                    if i['uid_id']==j.id:
                        break
            dics['nickname'] = j.nickname
            dics['isbanker'] = 0
            if i['uid_id'] == bank_uid:
                dics['isbanker'] = 1
            dics['score'] = i['score']
            dics['uid'] = i['uid_id']
            dics['head_img'] = j.head_img
            u_data.append(dics)
        datas['user_infos']=u_data
        if  u_data:
            t_data['list'].append(datas)

    #测试数据
    if IS_TEST:
        t_data={"win_rounds":2,"round_counts":3,"list":[{"recordid":"f4ece59c-80e6-11e7-b195-bc5ff4d56479","status":-1,"create_time":-1,"roomid":756937,"user_infos":[{"head_img":"http://andytest.nvzhanshen.com/pt/static/egret/150314184020_wqdzpy.png","isbanker":0,"nickname":"测试5test126","score":-20,"uid":21},{"head_img":"http://andytest.nvzhanshen.com/pt/static/egret/150314184020_wqdzpy.png","isbanker":1,"nickname":u"测试test126","score":20,"uid":45}]},
                                                    {"recordid":"293eaef4-80e5-11e7-b195-bc5ff4d56479","status":-1,"create_time":-1,"roomid":103955,"user_infos":[{"head_img":"http://andytest.nvzhanshen.com/pt/static/egret/150314184020_wqdzpy.png","isbanker":1,"nickname":"测试8bd5test126","score":3,"uid":45},{"head_img":"http://andytest.nvzhanshen.com/pt/static/egret/150314184020_wqdzpy.png","isbanker":0,"nickname":u"测试test126","score":-3,"uid":21}]},
                                                    {"recordid":"09aa2eaa-80e1-11e7-b195-bc5ff4d56479","status":-1,"create_time":-1,"roomid":681809,"user_infos":[{"head_img":"http://andytest.nvzhanshen.com/pt/static/egret/150314184020_wqdzpy.png","isbanker":1,"nickname":"测试d5test126","score":-18,"uid":21},{"head_img":"http://andytest.nvzhanshen.com/pt/static/egret/150314184020_wqdzpy.png","isbanker":0,"nickname":u"测试test126","score":18,"uid":45}]}],"allscore":6}

    objs['msg'] = 'success'
    objs['data']=t_data
    return HttpResponse(ujson.dumps(objs))



#查看战绩小局
#http://127.0.0.1:8080/api/hall/zy/gamerecord_detail?roomid=853406&recordid=fffc45b8-6872-11e7-b195-bc5ff4d56479
#roomid 房间ID，recordid 房间编号
#{"msg":"success","code":0,"data":[
# {"room_info":{"round":1,"time":1502711536.0},"user_infos":[{"isbanker":0,"head_img":"http:\/\/andytest.nvzhanshen.com\/pt\/static\/egret\/150314184020_wqdzpy.png","score":-15,"nickname":"\u6d4b\u8bd5test102","id":21},{"isbanker":1,"head_img":"http:\/\/andytest.nvzhanshen.com\/pt\/static\/egret\/150314184020_wqdzpy.png","score":15,"nickname":"\u6d4b\u8bd5test126","id":45}]},
# {"room_info":{"round":1,"time":1502711536.0},"user_infos":[{"isbanker":0,"head_img":"http:\/\/andytest.nvzhanshen.com\/pt\/static\/egret\/150314184020_wqdzpy.png","score":-15,"nickname":"\u6d4b\u8bd5test102","id":21},{"isbanker":1,"head_img":"http:\/\/andytest.nvzhanshen.com\/pt\/static\/egret\/150314184020_wqdzpy.png","score":15,"nickname":"\u6d4b\u8bd5test126","id":45}]}
# ]}
#data为对象数组，room_info中round表示局数，time表示开始时间,
# user_infos所有表示用户信息和游戏得分,nickname,score,head_img,isbanker,uid对应为昵称、分数、头像、是否坐庄、玩家ID
@csrf_exempt
def user_each_gamerecord(request):
    objs={'code':0,'msg':'','data':[]}
    data=fun.Decode_Request_MJ(request)
    t_uid=None
    #fun.add_log(data)
    #print '--user_each_gamerecord--',data
    if request.method == 'GET':
        need_keys=['roomid','recordid']
        if check_args(data,need_keys):
            objs['msg']="error parms"
            objs['code'] = errcode.ParamError
            return HttpResponse(ujson.dumps(objs))

        roomid = data['roomid']
        recordid = data['recordid']
        t_uid=data.get('uid',None)
    elif request.method == 'POST':
        roomid = request.POST.get('roomid',None)
    #print data,t_uid
    #排序玩家数据，自己的第1
    def sortUer():
        uarr=u_list+[]
        uarr.sort(key = lambda x:x["uid"])#uid排序
        #print data,'---data----',t_uid
        if t_uid:
            t_index=None
            t_item=None
            for ii in range(len(uarr)):
                if uarr[ii]['uid']==int(t_uid):
                    t_index=ii
                    t_item=uarr[ii]
                    break
            if t_index:
                del uarr[t_index]
                uarr.insert(0,t_item)
            #print t_index,u_list,'--sortUer--',uarr
        return uarr

    # if not GameRecord.objects.filter(roomid=roomid).exists():
    #     print roomid
    #     objs['msg']='error roomid'
    #     objs['code']=errcode.TableNotExists
    #     return HttpResponse(ujson.dumps(objs))
    #date_from = fun.GetTime_ByNow(-webconfig.GAME_RECORD_DAY),start_time__gte=date_from
    all_infos = GameRecord.objects.filter(roomid=roomid,recordid=data['recordid']).order_by('roundid')
    cur_round=all_infos[0].roundid#first rounud
    u_list = []#所有玩玩家信息
    dic = {}#单个玩家信息
    record_arr = []#每局的信息数组
    cur_time=None#时间
    #用户头像
    uimg_obj={}
    dictss=None
    #房间信息
    tb_info=TableInfo.objects.get(roomid=roomid,recordid=recordid)
    bank_uid=tb_info.uid_id
    for i in all_infos:
        if cur_round!=i.roundid:
            #保存某局
            u_list=sortUer()#uid排序
            dictss={'room_info':{'time': cur_time,'round':cur_round},'user_infos': u_list}
            record_arr.append(dictss)
            #新的一局
            cur_round =i.roundid
            u_list = []
            cur_time=None
            dictss=None

            #还是当前局的玩家
        dic['nickname'] = i.nickname
        dic['score'] = i.score
        dic['isbanker'] = 0
        if bank_uid==i.uid_id:
            dic['isbanker'] = 1
        cur_uid=i.uid_id
        if cur_uid not in uimg_obj:
            uimg_obj[cur_uid]=UserInfo.objects.get(id=cur_uid).head_img#用一条语句获取
        dic['head_img'] = uimg_obj[cur_uid]
        dic['uid'] = cur_uid
        u_list.append(dic)
        if not cur_time:
            cur_time=mjhall.DateTimeToTimetuple(i.start_time)
        #print i.start_time,'--i.start_time--',cur_time
        dic = {}
    #最后一局
    #print dictss,'--dictss--',len(all_infos)
    if u_list:
        u_list=sortUer()#uid排序
        record_arr.append({'room_info':{'time': cur_time,'round':cur_round},'user_infos': u_list})

    #测试数据
    if IS_TEST:
        record_arr=[{"room_info":{"round":1,"time":1502711536.0},"user_infos":[{"isbanker":0,"head_img":"http://andytest.nvzhanshen.com/pt/static/egret/150314184020_wqdzpy.png","score":-15,"nickname":"我啊8bd5test102","uid":21},{"isbanker":1,"head_img":"http://andytest.nvzhanshen.com/pt/static/egret/150314184020_wqdzpy.png","score":15,"nickname":"不是8bd5test126","uid":45}]},
                {"room_info":{"round":1,"time":1502711536.0},"user_infos":[{"isbanker":0,"head_img":"http://andytest.nvzhanshen.com/pt/static/egret/150314184020_wqdzpy.png","score":-15,"nickname":"你是8bd5test102","uid":21},{"isbanker":1,"head_img":"http://andytest.nvzhanshen.com/pt/static/egret/150314184020_wqdzpy.png","score":15,"nickname":"留个脚印8bd5test126","id":45}]}]

    objs['code'] = errcode.Success
    objs['data']=record_arr
    #objs['data'].append(dics)
    objs['msg'] = 'success'
    return HttpResponse(ujson.dumps(objs))



#我的房间
#http://127.0.0.1:8080/api/hall/zy/myroom?uid=1&appid=zytx123
#http://127.0.0.1:8080/api/hall/zy/myroom?uid=100&appid=yuanlaimj123
# uid u'用户帐号',appid平台号
#{"msg":"","code":0,"data":{"create":[{"gameId":55,"playnum":0,"createTs":1502718897.0,"rule":{"555":10,"553":0},"state":0,"roomId":766648},
# {"gameId":55,"playnum":0,"maxum":4,"createTs":1502718868.0,"rule":{"555":10,"553":0},"state":0,"roomId":310691,users:['测试1','玩家2']},
# {"gameId":55,"playnum":0,"maxum":4,"createTs":1502718473.0,"rule":{"555":10,"553":0},"state":0,"roomId":354989,users:['测试1','玩家2']},
# {"gameId":55,"playnum":0,"maxum":4,"createTs":1502717530.0,"rule":{"555":10,"553":0},"state":0,"roomId":902161,users:['测试1','玩家2']},
# {"gameId":55,"playnum":0,"maxum":4,"createTs":1502717359.0,"rule":{"555":10,"553":0},"state":0,"roomId":978852,users:['测试1','玩家2']},
# {"gameId":55,"playnum":0,"maxum":4,"createTs":1502715736.0,"rule":{"555":10,"553":0},"state":0,"roomId":297929,users:['测试1','玩家2']},
# {"gameId":55,"playnum":0,"maxum":4,"createTs":1502715119.0,"rule":{"555":10,"553":0},"state":0,"roomId":833821,users:['测试1','玩家2']}],"join":[]}}
#gameId游戏id,playnum人数,maxum满人数，createTs时间，rule玩法openparm，state状态（0没开始，4进行中，其它为解散），roomId房间号,users玩家列表)
@csrf_exempt
def user_get_myroom(request):
    t_obj=fun.Decode_Request_MJ(request)
    fun.add_log(t_obj)

    t_uid=None
    t_data={'code':-1,'msg':'','data':{}}
    t_appid=None
    if request.method == 'GET':
        need_keys=['uid','appid']
        if check_args(t_obj,need_keys):
            t_data['msg']="error parms"
            return HttpResponse(ujson.dumps(t_data))
        t_uid = t_obj['uid']
        t_appid=t_obj.get('appid',None)

    elif request.method == 'POST':
        t_uid = request.POST.get('uid',None)

    if not t_uid:
        t_data['msg']="empty http uid"
        t_data['code']=errcode.UserNotExists
        return HttpResponse(ujson.dumps(t_data))

    #根据appid获取游戏列表
    t_games=None
    if t_appid:
        t_games=mjhall.get_PlatformInfo_Games(t_appid)
    # if not t_games:
    #     t_data['msg']="empty games"
    #     t_data['code']=errcode.DB_DataNotExists
    #     return HttpResponse(ujson.dumps(t_data))

    #判断用户是否存在,game_status__in=webconfig.ROOM_NORMAL_STATUS,game_status__in=webconfig.ROOM_NORMAL_STATUS,
    if(UserInfo.objects.filter(pk=t_uid).exists()):
        #redis对象
        rc = db_redis.get_redis()
        #获取全部的正常桌
        date_to=datetime.datetime.now()
        date_from=fun.GetTime_ByNow(-1)
        cur_filter=TableInfo.objects.filter(uid_id=t_uid,create_time__gte=date_from)
        if t_games!=None:
            cur_filter=cur_filter.filter(gameid_id__in=t_games)
        if not IS_TEST:
            cur_filter=cur_filter.filter(game_status__in=webconfig.ROOM_NORMAL_STATUS)

        tbs=cur_filter.order_by('-id')

        t_create=[]
        t_join=[]
        #print t_games,date_from,'--date_from--',webconfig.ROOM_NORMAL_STATUS,t_uid,tbs
        for ii in tbs:
            cur_gid=ii.gameid_id
            #游戏ID  当前人数 房间号 玩法 当前状态 创建时间
            cur_obj={'gameId':cur_gid,'roomId':ii.roomid,'state':ii.game_status,'rule':ii.openparam,'createTs':mjhall.DateTimeToTimetuple(ii.create_time),
                     'playnum':0,'maxum':GAME_TO_NUMBER.get(cur_gid,4)}
            #桌子人数要从redis中读取,game_online_玩家uid,值是1_123123，游戏id_房间号
            rc_key='online_%s_%s'%(cur_gid,ii.roomid)
            cur_obj['playnum']=len(rc.smembers(rc_key))
            #规则
            if len(cur_obj['rule'])>0:
                cur_obj['rule']=ujson.loads(cur_obj['rule'])
            # #玩家列表
            # wis=WithholdInfo.objects.filter(tableid_id=ii.pk).values("uid__nickname")
            # for ii_wi in wis:
            #     cur_obj['users'].append(ii_wi['uid__nickname'])

            #服务器的信息
            cur_obj['host']=''
            cur_obj['port']=''
            ii_ser= ii.server
            if ii_ser:
                cur_obj['host']=ii_ser.ip
                cur_obj['port']=ii_ser.port

            t_create.append(cur_obj)

        #测试数据
        if IS_TEST:
            t_create=[{"gameId":55,"playnum":0,"maxum":5,"createTs":1502718897.0,"rule":{"555":10,"551":0,"552":1,"553":1},"state":0,"roomId":766648},
 {"gameId":54,"playnum":1,"maxum":10,"createTs":1502718968.0,"rule":{"555":10,"552":1,"553":0},"state":4,"roomId":310691},
 {"gameId":55,"playnum":0,"maxum":6,"createTs":1502718473.0,"rule":{"555":10,"552":0,"553":0},"state":0,"roomId":354989},
 {"gameId":56,"playnum":2,"maxum":7,"createTs":1502717530.0,"rule":{"555":10,"553":1,"553":0,"554":1},"state":4,"roomId":902161},
 {"gameId":55,"playnum":0,"maxum":8,"createTs":1502717359.0,"rule":{"555":10,"552":0,"553":0,"554":2},"state":0,"roomId":978852},
 {"gameId":54,"playnum":3,"maxum":9,"createTs":1502715736.0,"rule":{"555":10,"552":0,"553":0,"554":1},"state":0,"roomId":297929},
 {"gameId":56,"playnum":0,"maxum":4,"createTs":1502715119.0,"rule":{"555":10,"552":1,"553":0,"554":2},"state":0,"roomId":833821}]

        t_data['data']['create']=t_create
        t_data['data']['join']=t_join
        t_data['code']=0

        #fun.add_log(t_data)
        return HttpResponse(ujson.dumps(t_data))
    else:#新增
        t_data['msg']="empty uid"
        t_data['code']=errcode.UserNotExists
        return HttpResponse(ujson.dumps(t_data))

